{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "\n",
    "\n",
    "def dfs(nums, length, depth, path, used, res):\n",
    "    if depth == length: # path从根节点到叶子节点遍历完\n",
    "        # 添加路径的副本而不是引用本身\n",
    "        res.append(path[:])  # 添加一个全排列(路径)结果\n",
    "        return\n",
    "\n",
    "    for i in range(length):\n",
    "        if used[i]:\n",
    "            continue\n",
    "        path.append(nums[i])  # 入栈\n",
    "        used[i] = True\n",
    "        dfs(nums, length, depth + 1, path, used, res)\n",
    "        path.pop()  # 出栈 回溯\n",
    "        used[i] = False\n",
    "\n",
    "\n",
    "class Solution:\n",
    "    def permute(self, nums: List[int]) -> List[List[int]]:\n",
    "        length = len(nums)\n",
    "        if length == 0:\n",
    "            return [[]]\n",
    "\n",
    "        path = []  # stack 回溯路径\n",
    "        used = [False for _ in range(length)]  #\n",
    "        res = []  # 全排列结果\n",
    "        dfs(nums, length, 0, path, used, res)\n",
    "        return res\n"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "base",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.11.8"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
